from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from app.crud.logCrud import (
    get_log, get_logs, create_log, update_log, delete_log, get_logs_with_count
)
from app.schemas.logSchema import Log, LogCreate, PaginatedLogResponse
from app.database import get_db
from typing import Optional  # 确保导入 Optional

router = APIRouter(prefix="/api/v1", tags=["Logs"])

@router.post("/logs/", response_model=Log)
async def create_log_endpoint(
        log: LogCreate,
        db: AsyncSession = Depends(get_db)
):
    """创建新的日志记录

    - **action**: 操作类型（如"create", "update", "delete"）
    - **details**: 操作详情（JSON字符串或详细描述）
    """
    return await create_log(db, log=log)

@router.get("/logs/", response_model=PaginatedLogResponse)
async def read_logs(
    skip: int = 0,
    limit: int = 100,
    action: Optional[str] = None,  # 新增：按 action 过滤
    db: AsyncSession = Depends(get_db)
):
    """获取日志列表（支持分页和条件查询）

    - **skip**: 跳过的记录数（默认0）
    - **limit**: 每页返回的最大记录数（默认100）
    - **action**: 按操作类型过滤（可选）
    """
    #logs = await PaginatedLogResponse(db, skip=skip, limit=limit, action=action)
    data = await get_logs_with_count(db, skip=skip, limit=limit, action=action)
    return PaginatedLogResponse(**data)
    #return logs

# @router.get("/logs/", response_model=List[Log])
# async def read_logs(
#         skip: int = 0,
#         limit: int = 100,
#         db: AsyncSession = Depends(get_db)
# ):
#     """获取日志列表（分页）
#
#     - **skip**: 跳过的记录数（默认为0）
#     - **limit**: 每页返回的最大记录数（默认为100）
#     """
#     logs = await get_logs(db, skip=skip, limit=limit)
#     return logs


@router.get("/logs/{log_id}", response_model=Log)
async def read_log(
        log_id: int,
        db: AsyncSession = Depends(get_db)
):
    """根据ID获取单个日志记录

    - **log_id**: 要查询的日志ID
    """
    db_log = await get_log(db, log_id=log_id)
    if db_log is None:
        raise HTTPException(status_code=404, detail="Log not found")
    return db_log


@router.put("/logs/{log_id}", response_model=Log)
async def update_log_endpoint(
        log_id: int,
        log: LogCreate,
        db: AsyncSession = Depends(get_db)
):
    """更新日志记录

    - **log_id**: 要更新的日志ID
    - **action**: 新的操作类型
    - **details**: 新的操作详情
    """
    db_log = await update_log(db, log_id=log_id, log=log)
    if db_log is None:
        raise HTTPException(status_code=404, detail="Log not found")
    return db_log


@router.delete("/logs/{log_id}", response_model=Log)
async def delete_log_endpoint(
        log_id: int,
        db: AsyncSession = Depends(get_db)
):
    """删除日志记录

    - **log_id**: 要删除的日志ID
    """
    db_log = await delete_log(db, log_id=log_id)
    if db_log is None:
        raise HTTPException(status_code=404, detail="Log not found")
    return db_log